﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Ether;
using Ether.Libs;
using Jitter.LinearMath;

namespace Ether.Mapping
{
    public class CellPrim : PhysicsPrim
    {
        private CellType Type;
        private Vector3 OriginalPos;
        private int Level;

        public CellPrim(Vector3 pos, int level, CellType Type, CellRotation Rotation)
            : base(pos)
        {
            this.Type = Type;
            this.OriginalPos = pos;
            this.Level = level;
            switch (Type) {
                case CellType.None: this.Rescale(Vector3.Zero); AdjustHeight(level); break;
                case CellType.Normal: this.Rescale(EtherEngine.TileSize); AdjustHeight(level); break;
                case CellType.Solid: this.Rescale(EtherEngine.SolidScale); AdjustHeight(level); break;

                case CellType.Ramp:
                    {
                        this.Rescale(EtherEngine.RampScale);
                        AdjustHeight(level);
                        break;
                    }
            }

            SetRotation(Rotation);

            this.IsStatic = true;
            this.AffectedByGravity = false;            
        }

        public void Move(float x, float y, float z)
        {
            this.Position = this.Position + new JVector(x, y, z);
        }
        public void SetRotation(CellRotation Rotation)
        {
            this.Position = Conversion.ConvertVect(OriginalPos);
            this.AdjustHeight(Level);

            switch (Rotation) {
                case CellRotation.North: this.SetRotation(0, 90, 0); break;
                case CellRotation.East: this.SetRotation(0, 0, 0); break;
                case CellRotation.South: this.SetRotation(0, 270, 0); break;
                case CellRotation.West: this.SetRotation(0, 180, 0); break;
            }

            if (Type == CellType.Ramp)
            {
                switch (Rotation)
                {
                    case CellRotation.North: Move(0, .3f, 1f); break;
                    case CellRotation.East: Move(-1f, .3f, 0); break;
                    case CellRotation.South: Move(0, .3f, -1f); break;
                    case CellRotation.West: Move(1f, .3f, 0); break;
                }
            }
        }

        public Matrix World
        {
            get
            {
                return
                    Matrix.CreateScale(this.Scale)
                    *
                    Matrix.CreateRotationX(Rotation.X) *
                    Matrix.CreateRotationY(Rotation.Y) *
                    Matrix.CreateRotationZ(Rotation.Z)
                    *
                    Matrix.CreateTranslation(Conversion.ConvertVect(this.Position));
            }
        }
    }
}
